#! /bin/sh -
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: huangdi-prepare-firstboot.sh
# author: david921518@qq.com

. /usr/lib/kpc/posix-arrays.sh

################
# global vars
GLB_WORK_DIR=
GLB_DONE_FILE=
GLB_FIRSTBOOT_ROOT=
GLB_REBOOT_COUNTER=
#GLB_INSTALLED_PKGS=()
declare_i_arr GLB_INSTALLED_PKGS
GLB_NUM_INSTALLED_PKGS=0
GLB_REAL_PATH=
################

whoami=$(which whoami)
if [ x"$whoami" == x ]; then
  user="$USER"
else
  user=$(whoami)
fi

log_kmsg_path="/dev/kmsg"
log_con_path="/dev/tty1"

# 定义日志格式-前缀
log_prefix="[prepare-firstboot]"
# 定义日志目录和文件名
if [ "$user" == "root" ]; then
  log_file_dir="/var/log/kpc/huangdi"
else
  log_file_dir=~/.local/log/kpc/huangdi
fi
log_file_name="firstboot.log"
log_file_path="$log_file_dir/$log_file_name"

function log_init()
{
  # 文件不存在则创建
  if [ ! -d "$log_file_dir" ]; then
    mkdir -p $log_file_dir
    chmod -R 755 $log_file_dir
  fi
  if [ ! -f "$log_file_path" ]; then
    touch $log_file_path
  fi
}

# 定义日志打印格式
function log()
{
  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")
  echo "$curtime $log_prefix $@"
  echo "$curtime $log_prefix $@" >> $log_file_path
  #sleep 1
  if [ "$user" == "root" ]; then
    echo "$log_prefix [kmsg] $@" > $log_kmsg_path
    sleep 1
    #echo "$curtime $log_prefix [con] $@" > $log_con_path
    #sleep 1
  fi
}

function log_from_file()
{
  tmpfile=$@
  if [ ! -f "$tmpfile" ]; then
    log "no file [$tmpfile] to log"
    return 1
  fi

  declare_i_arr lists
  while IFS= read -r line;
  do
    add_i_arr_el lists "$line"
  done <$tmpfile

  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")

  #echo "$curtime $log_prefix $@"
  #echo "$curtime $log_prefix $@" >>$log_file_path
  local i=0
  get_i_arr_indices lists indices
  for i in $indices
  do
    echo "$curtime $log_prefix ${line}"
    echo "$curtime $log_prefix ${line}" >>$log_file_path
  done

  if [ "$user" == "root" ]; then
    #echo "$log_prefix [kmsg] $@" >$log_kmsg_path
    get_i_arr_indices lists indices
    for i in $indices
    do
      echo "$curtime $log_prefix ${line}" >$log_kmsg_path
      [ $(( i%10 )) -ne 9 ] || sleep 1
    done

    #sleep 1

    #echo "$curtime $log_prefix [con] $@" >$log_con_path
    #for i in $( seq 0 $((${#lists[*]} - 1)) )
    #do
    #  echo "$curtime $log_prefix ${lists[i]}" >$log_con_path
    #done

    #sleep 1
  fi
}

# loop forever to reboot
function force_reboot()
{
  log "force reboot now!"
  while true; do reboot; sleep 9; done
}

# clean up sysupgrade script
function cleanup_sysupgrade_script()
{
  local sysupgrade_file=/etc/zzz-sysupgrade
  if [ -f $sysupgrade_file ]; then
    log "rm -f $sysupgrade_file"
    rm -f $sysupgrade_file
  fi
}

# fix all kinds of possible broken issues
function fix_possible_broken()
{
  #log "do nothing!!!"
  local is_opkg=$(which opkg)
  if [ x"$is_opkg" == x ]; then
    log "Not ipk package managing system!!!"
  else
    opkg update
    # base tools
    opkg install coreutils-whoami
    opkg install coreutils-realpath
    opkg install curl
    # manipulate partition tools
    opkg install parted
    opkg install losetup
    opkg install resize2fs
    opkg install blkid
    opkg install lsblk
    # upgrade system
    opkg install owut
  fi
}

# get Work Dir
function get_work_dir()
{
  ################
  # /etc/kpc/firstboot/guest/huangdi-prepare-firstboot.sh
  # /etc/kpc/firstboot/guest/huangdi-first-boot.sh
  # /etc/kpc/firstboot/root/etc/rc.local
  # /etc/rc.local
  # /kpcos/distro/huangdi/releases/1.04/targets/x86/64/guest/huangdi-prepare-firstboot.sh
  # /kpcos/distro/huangdi/releases/1.04/targets/x86/64/root/etc/rc.local
  ################

  local real_path=$(realpath $0)
  GLB_REAL_PATH="$real_path"
  log "REAL PATH is [$GLB_REAL_PATH]"

  GLB_WORK_DIR=$(dirname "$real_path")
  log "WORK DIR is [$GLB_WORK_DIR]"

  local done_file="${real_path}_done"
  log "done_file=[$done_file]"
  real_done_file=$(realpath "$done_file")
  log "real_done_file=[$real_done_file]"

  GLB_DONE_FILE="$real_done_file"
  log "GLB_DONE_FILE=[$GLB_DONE_FILE]"

  local firstboot_root="$GLB_WORK_DIR/../root"
  log "firstboot_root=[$firstboot_root]"
  real_firstboot_root=$(realpath "$firstboot_root")
  log "real_firstboot_root=[$real_firstboot_root]"

  if [ ! -d $real_firstboot_root ]; then
    log "No firstboot root dir [$real_firstboot_root]."
    exit 1
  fi

  GLB_FIRSTBOOT_ROOT="$real_firstboot_root"
  log "GLB_FIRSTBOOT_ROOT=[$GLB_FIRSTBOOT_ROOT]"

  GLB_REBOOT_COUNTER=$GLB_WORK_DIR/reboot_counter
  log "GLB_REBOOT_COUNTER=$GLB_REBOOT_COUNTER"
  if [ ! -f $GLB_REBOOT_COUNTER ]; then
    echo "0" >$GLB_REBOOT_COUNTER
  fi
}

function check_reboot_counter()
{
  local reboot_counter=$(cat $GLB_REBOOT_COUNTER)
  reboot_counter=$((reboot_counter + 1))
  log "reboot counter is [$reboot_counter]"
  if [ $reboot_counter -gt 9 ]; then
    log "reboot too many times, exit now!"
    exit 1
  else
    log "set reboot counter to [$reboot_counter]"
    echo "$reboot_counter" >$GLB_REBOOT_COUNTER
  fi
}

function reset_reboot_counter()
{
  log "reset reboot counter"
  echo "0" >$GLB_REBOOT_COUNTER
}

# save installed packages list
function save_pkg_list()
{
  if [ "$1" == "" ]; then
    log "save_pkg_list() filename is empty, do nothing!"
    return
  fi
  local list_file="$PWD"/$1
  log "save $inst_type packages list to $list_file"
  [ -f $list_file ] || opkg list-installed >$list_file
}

# start kpc-heartbeat
function start_heartbeat()
{
  heartbeat_conf_dir=/etc/kpc
  heartbeat_conf_file=/etc/kpc/heartbeat.conf
  heartbeat_file=/usr/sbin/kpc-heartbeat.sh
  heartbeat_lock=/tmp/kpc-hearbeat.lock
  if [ ! -f $heartbeat_conf_file ]; then
    mkdir -p $heartbeat_conf_dir
    echo 9 >$heartbeat_conf_file
  fi
  if [ -x $heartbeat_file ]; then
    log "start kpc-heartbeat"
    (flock -n $heartbeat_lock -c "($heartbeat_file)")&
  fi
}

# run bootstrap configurating
function run_bootstrap_config()
{
  local wifi_backend=""
  local wifi_dev=""
  local wifi_addr=""
  local wifi_mode=""
  local wifi_net=""
  local wifi_pass=""

  local conf_file=/etc/kpc/bootstrap.conf
  if [ -f $conf_file ]; then
    log "start to configurate bootstrap environment"

    declare_i_arr lists
    while IFS= read -r line;
    do
      add_i_arr_el lists "$line"
    done <$conf_file

    local i=0
    get_i_arr_indices lists indices
    for i in $indices
    do
      get_i_arr_val lists $i line
      #log "lists[$i]=[${line}]"
      local name=$(echo ${line} | awk '{print $1}')
      local val=$(echo ${line} | awk '{print $2}')
      #log "name=[$name] val=[$val]"
      case "$name" in
        "#"* )
          #log "it's comment"
          ;;
        "" )
          #log "it's empty line"
          ;;
        "wifi.backend" )
          if [ "$val" == "iwd" ]; then
            log "enable iwd network configuration"
            wifi_backend="$val"
            iwd_main_conf=/etc/iwd/main.conf
            sed "s/#EnableNetworkConfiguration=true/EnableNetworkConfiguration=true/g" -i $iwd_main_conf
            #log_from_file $iwd_main_conf
          fi
          ;;
        "wifi.device_name" )
          wifi_dev="$val"
          log "wifi_dev=[$wifi_dev]"
          ;;
        "wifi.device_address" )
          wifi_addr="$val"
          log "wifi_addr=[$wifi_addr]"
          ;;
        "wifi.mode" )
          wifi_mode="$val"
          log "wifi_mode=[$wifi_mode]"
          ;;
        "wifi.network" )
          wifi_net="$val"
          log "wifi_net=[$wifi_net]"
          ;;
        "wifi.passphrase" )
          wifi_pass="$val"
          log "wifi_pass=[$wifi_pass]"
          ;;
        * )
          log "unknown option=[$name]"
          ;;
      esac
    done

    if [ "$wifi_backend" == "iwd" ]; then
      log "systemctl --now enable iwd"
      systemctl --now enable iwd
      sleep 3
      if [ x"$wifi_dev" == x ]; then
        #iwctl device list
        line=$(iwctl device list | grep "station" )
        log "line=[$line]"
        if [ x"$line" == x ]; then
          log "no station mode wifi device found, exit now"
          exit 1
        fi
        #dummy=$(echo $line | awk '{print $1}')
        dummy=$(echo $line | awk '{print $1}')
        log "dummy=[$dummy]"
        #dev_name=$(echo $line | awk '{print $2}')
        wifi_dev=$(echo $line | awk '{print $2}')
        log "wifi_dev=[$wifi_dev]"
        #dev_addr=$(echo $line | awk '{print $3}')
        wifi_addr=$(echo $line | awk '{print $3}')
        log "wifi_addr=[$wifi_addr]"
        #dev_powered=$(echo $line | awk '{print $4}')
        wifi_powered=$(echo $line | awk '{print $4}')
        log "wifi_powered=[$wifi_powered]"
        #dev_adapter=$(echo $line | awk '{print $5}')
        wifi_adapter=$(echo $line | awk '{print $5}')
        log "wifi_adapter=[$wifi_adapter]"
        #dev_mode=$(echo $line | awk '{print $6}')
        wifi_mode=$(echo $line | awk '{print $6}')
        log "wifi_mode=[$wifi_mode]"

        log "detect wifi_dev=[$wifi_dev]"
        if [ x"$wifi_dev" == x ]; then
          log "no wifi device found, exit now"
          exit 1
        fi
      fi
      if [ x"$wifi_dev" != x ]; then
        line=$(iwctl device list | grep " $wifi_dev " )
        log "line=[$line]"
        if [ x"$line" != x ]; then
          dummy=$(echo $line | awk '{print $1}')
          dev_name=$(echo $line | awk '{print $2}')
          dev_addr=$(echo $line | awk '{print $3}')
          dev_powered=$(echo $line | awk '{print $4}')
          dev_adapter=$(echo $line | awk '{print $5}')
          dev_mode=$(echo $line | awk '{print $6}')
          log "dev_mode=[$dev_mode]"
          if [ "$dev_mode" == "station" ]; then
            #iwctl station wlan0 scan
            tmpfile=$(mktemp)
            iwctl station $wifi_dev scan 2>&1 | tee $tmpfile
            log_from_file $tmpfile
            rm -f $tmpfile
            sleep 3

            #iwctl station wlan0 get-networks
            tmpfile=$(mktemp)
            iwctl station $wifi_dev get-networks 2>&1 | tee $tmpfile
            log_from_file $tmpfile
            rm -f $tmpfile

            #iwctl --passphrase "mysecret" station wlan0 connect "SSID"
            log "iwctl --passphrase $wifi_pass station $wifi_dev connect $wifi_net"
            iwctl --passphrase "$wifi_pass" station $wifi_dev connect "$wifi_net"
            sleep 3

            #iwctl station wlan0 show
            tmpfile=$(mktemp)
            iwctl station $wifi_dev show 2>&1 | tee $tmpfile
            log_from_file $tmpfile
            rm -f $tmpfile
            log "/etc/init.d/iwd restart"
            /etc/init.d/iwd restart
            sleep 1
          fi
        fi
      fi
      #iwctl station wlan0 scan
      #iwctl station wlan0 get-networks
      #iwctl --passphrase "mysecret" station wlan0 connect "SSID"
      #iwctl station wlan0 show
      #/etc/init.d/iwd restart
      #iwctl station wlan0 disconnect
    fi #endof wifi_backend==iwd
  fi
}

# check WAN interface
function check_wan_iface()
{
  local COUNTER=0
  local dev_array="$(ip route | awk '/default/ {print $5}')"
  local iface_dev=$(echo $dev_array | awk '{print $1}')
  while [ "$iface_dev"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get default route device interface, exit now"
      exit 1
    fi
    dev_array="$(ip route | awk '/default/ {print $5}')"
    iface_dev=$(echo $dev_array | awk '{print $1}')
  done

  COUNTER=0
  local WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  while [ "${WAN_IP}"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get WAN IP address, reboot now"
      force_reboot
    fi
    WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  done
  log "WAN IP=[${WAN_IP}]"
}

function make_firstboot_service()
{
  # generate /etc/zzz-firstboot
  zzz_firstboot=/etc/zzz-firstboot
  firstboot_lock=/tmp/.first-boot.lock

  log "make $zzz_firstboot"

  firstboot_file=$(realpath "$GLB_WORK_DIR/huangdi-first-boot.sh")

  if [ ! -f $firstboot_file ]; then
    log "No first boot script $firstboot_file"
  fi

  if [ ! -x $firstboot_file ]; then
    log "first boot script $firstboot_file is not executive"
  fi

  if [ ! -f $zzz_firstboot ]; then
    touch $zzz_firstboot
    cat <<EOF >>$zzz_firstboot
#!/bin/sh -e

if [ -x $firstboot_file ]; then
  (flock -x $firstboot_lock -c "$firstboot_file")&
fi
EOF
    chmod a+x $zzz_firstboot
  else
    real_zzz_firstboot=$(realpath $zzz_firstboot)
    sed "s#/etc/kpc/firstboot/guest/huangdi-first-boot.sh#$firstboot_file#g" -i $real_zzz_firstboot
    chmod a+x $real_zzz_firstboot
  fi
}

# 0. init script
log_init
log "[prepare-firstboot] START"
cleanup_sysupgrade_script
fix_possible_broken
get_work_dir
if [ -f $GLB_DONE_FILE ]; then
  log "exist file $GLB_DONE_FILE , exit now"
  exit 1
fi
cd "$GLB_WORK_DIR"
check_reboot_counter
start_heartbeat
run_bootstrap_config
check_wan_iface
save_pkg_list pre_prepare_firstboot_pkgs.txt

log "PATH=[$PATH]"

# 1. banner
if [ -f "$GLB_FIRSTBOOT_ROOT/etc/banner" ]; then
  log "copy $GLB_FIRSTBOOT_ROOT/etc/banner to /etc/banner"
  cp -f "$GLB_FIRSTBOOT_ROOT"/etc/banner /etc/banner
fi

# 2. /etc
if [ -e "$GLB_FIRSTBOOT_ROOT/etc" ]; then
  log "copy $GLB_FIRSTBOOT_ROOT/etc/* to /etc/"
  #cp -af "$GLB_FIRSTBOOT_ROOT"/etc/* /etc/
  for file in $(ls -A $GLB_FIRSTBOOT_ROOT/etc/); do
    cp -af "$GLB_FIRSTBOOT_ROOT/etc/$file" /etc/
  done
fi

# 3. /usr/lib
if [ -e "$GLB_FIRSTBOOT_ROOT/usr/lib" ]; then
  log "copy $GLB_FIRSTBOOT_ROOT/usr/lib/* to /usr/lib/"
  #cp -af "$GLB_FIRSTBOOT_ROOT"/usr/lib/* /usr/lib/
  for file in $(ls -A $GLB_FIRSTBOOT_ROOT/usr/lib/); do
    cp -af "$GLB_FIRSTBOOT_ROOT/usr/lib/$file" /usr/lib/
  done
fi

# 4. /usr/sbin
if [ -e "$GLB_FIRSTBOOT_ROOT/usr/sbin" ]; then
  log "copy $GLB_FIRSTBOOT_ROOT/usr/sbin/* to /usr/sbin/"
  #cp -af "$GLB_FIRSTBOOT_ROOT"/usr/sbin/* /usr/sbin/
  for file in $(ls -A $GLB_FIRSTBOOT_ROOT/usr/sbin/); do
    cp -af "$GLB_FIRSTBOOT_ROOT/usr/sbin/$file" /usr/sbin/
  done
fi

# 5. generate zzz-firstboot based on $GLB_WORK_DIR
make_firstboot_service

save_pkg_list post_prepare_firstboot_pkgs.txt
touch $GLB_DONE_FILE
sync
#sleep 1

log "[prepare-firstboot] EXIT"
#sleep 1

# restart system
reset_reboot_counter
#poweroff
